package com.atguigu.gmall.pay.paynotify;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.config.mq.MqService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.pay.config.properties.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author lhh
 * @ClassName PaySuccessNotifyController
 * @date 2022 2022/12/26
 */
@Slf4j
@RequestMapping("/api/payment")
@RestController
public class PaySuccessNotifyController {

    @Resource
    AlipayProperties alipayProperties;

    @Resource
    MqService mqService;

    /**
     * 支付成功以后支付宝会给我们这里发送通知
     *
     * @param params
     * @return
     */
    @PostMapping("/notify/success")
    public String paySuccessNotify(@RequestParam Map<String, String> params) throws AlipayApiException {

        log.info("收到支付宝支付消息通知：{}", JSON.toJSONString(params));
        //验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(),
                alipayProperties.getSignType());
        if (signVerified) {
            //修改订单状态
            log.info("验签通过，准备修改订单状态");
            String trade_status = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(trade_status)) {
                mqService.send(params, MqConst.ORDER_EVENT_EXCHANGE,MqConst.ORDER_PAYED_RK);
            }
        } else {
            log.error("支付的错误信息");
        }

        return "success";
    }


}
